package servlets;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import clases.Response;

import com.google.gson.Gson;

import constantes.Constantes;
import services.ComentarioServiceIntf;

@Component("comentarios")
public class Comentarios extends HttpServlet implements HttpRequestHandler{

	private static final long serialVersionUID = 1L;

	private static int operacion;
	private static String coment;
	private static Long idA;
	private static Long idU;

	@Autowired
	private ComentarioServiceIntf comentarioService;

	@SuppressWarnings("unchecked")
	public void handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		System.out.println("COMENTARIOS");

		Enumeration<String> parametros = arg0.getParameterNames();

		while (parametros.hasMoreElements()) {
			String parametro= (String) parametros.nextElement();
			switch(parametro){
			case "_OPERACION":
				operacion = Integer.parseInt((String) arg0.getParameter(parametro));
				break;
			case "_ID_A":
				idA = new Long((String)arg0.getParameter(parametro));
				break;
			case "_ID_U":
				idU =  new Long((String)arg0.getParameter(parametro));
				break;
			case "_COMENT":
				coment =  (String)arg0.getParameter(parametro);
				break;

			default:
				break;

			}
		}

		ejecutaOperacion(arg1);


	}

	private void ejecutaOperacion(HttpServletResponse response) throws IOException {
		Gson gson = new Gson();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		Response ok = new Response();

		switch(operacion){
		case 1://GetByActividad
			try{
				ok.setObject(gson.toJson(comentarioService.getComentariosEvento(idA)));
				ok.setOk(true);
				ok.setComent(Constantes.COMENTARIO_VACIO);
				response.getWriter().write(gson.toJson(ok));
			}catch (Exception e) {
				ok.setOk(false);
				ok.setComent(e.getMessage());
				response.getWriter().write(gson.toJson(ok));
			}


			break;
		case 2://Nuevo
			try{
				comentarioService.guardaComentario(coment, idA, idU);
				ok.setOk(true);
				ok.setComent(Constantes.COMENTARIO_VACIO);
				response.getWriter().write(gson.toJson(ok));
			}catch (Exception e) {
				ok.setOk(false);
				ok.setComent(e.getMessage());
				response.getWriter().write(gson.toJson(ok));
			}
			break;
		
		default:
			break;
		}



	}

}
